package com.pan.admin.quartz.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.base.CollUtils;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.encode.Base64Utils;
import com.gitee.apanlh.util.log.Log;
import com.gitee.apanlh.util.log.LogLevel;
import com.gitee.apanlh.util.net.http.HttpClientBuilder;
import com.gitee.apanlh.util.net.http.HttpResponse;
import com.gitee.apanlh.web.http.HttpMethod;
import com.pan.admin.module.log.dao.SmsLogDao;
import com.pan.admin.module.log.entity.SmsLog;
import com.pan.admin.quartz.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 短信验证码
 *
 * @author Pan
 */
@Service
public class SmsServiceImpl implements SmsService {

    private static final String ACCOUNT = "szhh@szhh";
    private static final String PWD = "91ub08LI";

    @Autowired
    private SmsLogDao smsLogDao;

    @Override
    public void sendCrmNotice(List<String> phoneList, String orgName) {

        String msg = "" + orgName + "，您有新的用户申请，请及时查收。";

        try (ExecutorService pool = Executors.newVirtualThreadPerTaskExecutor()) {
            for (String phone : phoneList) {
                pool.execute(() -> sendSms(ACCOUNT, PWD, phone, msg));
            }
        }
    }

    /**
     * 发送短信消息
     *
     * @param account 账号
     * @param pwd     密码
     * @param phone   手机号
     * @param msg     消息
     */
    void sendSms(String account, String pwd, String phone, String msg) {
        String status = "1";
        //  记录开始时间
        long start = System.currentTimeMillis();
        //  请求头
        Map<String, String> headers = MapUtils.newHashMap();
        //  响应数据
        String str = "";

        Map<String, Object> bodyMap = MapUtils.newHashMap();
        Map<String, String> item = MapUtils.newHashMap(itemMap -> itemMap.put("to", phone));
        List<Map<String, String>> items = CollUtils.newArrayList(itemsList -> itemsList.add(item));
        bodyMap.put("items", items);
        bodyMap.put("content", msg);
        bodyMap.put("msgType", "sms");
        //  接收数据
        String reqJson = JSONObject.toJSONString(bodyMap);

        try {
            HttpResponse build = HttpClientBuilder.builder("http://sh.mosapi.cn:9051/api/v1.0.0/message/mass/send", HttpMethod.POST)
                    .withBodyJson(reqJson)
                    .withHeader((headerMap)->{
                        String authorization = Base64Utils.encodeToStr(account + ":" + MD5.create().digestToHex(pwd));
                        headerMap.put("Content-Type", "application/json;charset=utf-8");
                        headerMap.put("Accept", "application/json");
                        headerMap.put("Authorization", authorization);

                        //  保存请求头
                        headers.putAll(headerMap);
                    })
                    .withLogLevel(LogLevel.INFO)
                    .withErrorLogLevel(LogLevel.INFO)
                    .build();
            if (build.isError()) {
                status = "0";
                Log.get().warn("通知短信发送异常:{}", build.getErrorMsg());
                return ;
            }
            str = build.getStr();
            JSONObject jsonObject = JSONObject.parseObject(str);
            if (jsonObject == null || jsonObject.getInteger("code") != 0) {
                status = "0";
                Log.get().warn("通知短信发送失败, 手机号:[{}], 响应体:{}", phone, str);
            }
        } catch (Exception e) {
            status = "0";
            throw e;
        } finally {
            //  记录结束时间
            long end = System.currentTimeMillis();
            //  创建短信日志实体类
            SmsLog smsLog = new SmsLog();
            //  手机号
            smsLog.setPhone(phone);
            //  服务商名称
            smsLog.setProviderName("玄武云");
            //  短信类型
            smsLog.setType("发送crm人员短信通知");
            //  短信内容
            smsLog.setContext(msg);
            //  状态  0: 失败  1：成功
            smsLog.setStatus(status);
            //  请求地址
            smsLog.setReqUrl("http://sh.mosapi.cn:9051/api/v1.0.0/message/mass/send");
            //  请求头
            smsLog.setReqHeader(JsonUtils.toJson(headers));
            //  接收数据
            smsLog.setReqData(reqJson);
            //  响应数据
            smsLog.setRespData(str);
            //  耗时毫秒数
            smsLog.setTaskTime(end - start);
            //  创建时间
            smsLog.setCreateTime(new Date());

            smsLogDao.insert(smsLog);
        }
    }
}
